<template>
  <div class="material-selector">
    <el-input
      :model-value="selectedMaterial ? selectedMaterial.materialName : ''"
      placeholder="请选择物料"
      readonly
      class="selector-input"
    >
      <template #append>
        <el-button @click="openMaterialSelector">选择</el-button>
      </template>
    </el-input>
    
    <!-- 物料价格显示 -->
    <div v-if="selectedMaterial && showPrice" class="material-price">
      物料价格: <span>{{ selectedMaterial.purchasePrice || 0 }} 元</span>
    </div>
    
    <!-- 物料选择对话框 -->
    <material-dialog 
      ref="materialDialogRef"
      :multiple="false"
      @handleMaterialSelect="handleMaterialSelect"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, defineEmits, defineProps, watch } from 'vue'
import MaterialDialog from '@/views/baseInfo/deviceMaterial/index.vue'
import type { Material } from '@/api/material/type'

// 定义Props
const props = defineProps({
  modelValue: {
    type: Object,
    default: null
  },
  showPrice: {
    type: Boolean,
    default: true
  }
})

// 定义事件
const emit = defineEmits(['update:modelValue', 'change'])

// 组件状态
const materialDialogRef = ref()
const selectedMaterial = ref<Material | null>(null)

// 打开物料选择器
const openMaterialSelector = () => {
  materialDialogRef.value.onShow()
}

// 处理物料选择
const handleMaterialSelect = (material: Material) => {
  selectedMaterial.value = material
  emit('update:modelValue', material)
  emit('change', material)
}

// 监听modelValue变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      selectedMaterial.value = newVal as Material
    } else {
      selectedMaterial.value = null
    }
  },
  { immediate: true }
)
</script>

<style scoped lang="scss">
.material-selector {
  width: 100%;
  
  .selector-input {
    width: 100%;
    
    :deep(.el-input__wrapper) {
      padding-right: 0;
    }
    
    :deep(.el-input-group__append) {
      padding: 0;
      overflow: hidden;
    }
  }
  
  .material-price {
    margin-top: 5px;
    font-size: 12px;
    color: #666;
    
    span {
      color: #409EFF;
      font-weight: bold;
    }
  }
}
</style> 